from rest_framework.views import APIView
from luffy_city.libs.geetest import GeetestLib
from rest_framework.response import Response

from rest_framework.generics import CreateAPIView

from .models import User
from .serializers import UserModelSerializer


# Create your views here.
class GeetestCapchaAPIView(APIView):
    def get(self, request):
        """生成验证码的流水号"""
        user_id = 'test'
        gt = GeetestLib(settings.GEETEST["pc_geetest_id"], settings.GEETEST["pc_geetest_key"])
        status = gt.pre_process(user_id)
        response_str = gt.get_response_str()
        import json
        response = json.loads(response_str)
        return Response(response)

    def post(self, request):
        """校验验证码的结果"""
        gt = GeetestLib(settings.GEETEST["pc_geetest_id"], settings.GEETEST["pc_geetest_key"])
        challenge = request.data.get(gt.FN_CHALLENGE, '')
        validate = request.data.get(gt.FN_VALIDATE, '')
        seccode = request.data.get(gt.FN_SECCODE, '')
        result = gt.failback_validate(challenge, validate, seccode)
        result = {"status": "success"} if result else {"status": "fail"}
        return Response(result)


class UserAPIView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


from rest_framework import status
from django_redis import get_redis_connection
import random
from django.conf import settings


class SMAAPIView(APIView):
    """
    短信发送接口
    url:        /ueses/sms/?P<mobile>1[3-9]\d{9}/
    """

    def get(self, request, mobile):

        # 验证手机号
        try:
            User.objects.get(mobile=mobile)
            return Response({"message": "对不起，手机号已经被注册"}, status=status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            pass

        # 验证一分钟内是否发送过短信
        redis_conn = get_redis_connection("sms_code")
        ret = redis_conn.get("interval_%s" % mobile)
        if ret is not None:
            return Response({"message": "对不起，短信发送过于频繁"})

        # 生成短信的验证码
        sms_code = '%06d' % random.randint(100, 999999)

        # 保存短信的验证码  优化前
        # redis_conn.setex("键","时间","值")
        # redis_conn.setex("sms_%s" % mobile, settings.SMS['sms_expire_time'], sms_code)
        # redis_conn.setex('interval_%s' % mobile, settings.SMS['sms_interval_time'], '_')

        # 保存短信的验证码  优化后
        # 使用redis提供的事务配合管道[pipeline]操作来保证多条命令要么一起执行，要么一起失败！
        # redis的事务也只能控制数据的修改，设置和删除操作，对于获取数据来说，没必要使用事务！
        pipe = redis_conn.pipeline()  # 创建一个管道
        pipe.multi()  # 开启redis事务
        pipe.setex("sms_%s" % mobile, settings.SMS["sms_expire_time"], sms_code)
        pipe.setex("interval_%s" % mobile, settings.SMS["sms_interval_time"], "_")
        pipe.execute()  # 执行redis事务

        # 发送短信
        # 调用celery异步任务
        from my_celery.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)

        return Response({'message': '短信发送成功,请留意您的手机！'})
